<template>
    <div class="login-container">
        <h1>登录</h1>
        <form @submit.prevent="handleLogin">
            <div class="form-group">
                <label for="username">用户名</label>
                <input type="text" id="username" v-model="username" placeholder="请输入用户名" required />
            </div>
            <div class="form-group">
                <label for="password">密码</label>
                <input type="password" id="password" v-model="password" placeholder="请输入密码" required />
            </div>
            <button type="submit" class="login-btn">登录</button>
        </form>
        <div class="sync-buttons">
            <AButton type="primary" @click="beforeHandleDownloadSync">同步数据（下载）</AButton>
            <AButton @click="beforeHandleUploadSync">同步数据（上传）</AButton>
        </div>
        <a-modal v-model:open="showDownloadDialog" title="你确定要【同步数据（下载）】吗？" :confirmLoading="confirmLoading"
            @ok="handleDownloadSync" @cancel="cancelDelWoodStock()" ok-text="确定" cancel-text="取消">
        </a-modal>
        <a-modal v-model:open="showUploadDialog" title="你确定要【同步数据（上传）】吗？" :confirmLoading="confirmLoading"
            @ok="handleUploadSync" @cancel="cancelDelWoodStock()" ok-text="确定" cancel-text="取消">
        </a-modal>
    </div>
</template>

<script>
import { ref } from 'vue';
import { Button as AButton, message as AMessage, Popconfirm as APopconfirm } from 'ant-design-vue';
import { ipcApiRoute } from '@/api/main';
import { ipc } from '@/utils/ipcRenderer';
import axios from 'axios';
import PasswordEncoder from '@/utils/PasswordEncoder'; // 根据实际路径调整
import { useRouter } from 'vue-router';

export default {
    name: 'Login',
    setup() {
        const router = useRouter();
        const showDownloadDialog = ref(false);
        const showUploadDialog = ref(false);
        const username = ref('');
        const password = ref('');
        const confirmLoading = ref(false);
        const beforeHandleDownloadSync = async () => {
            const count = await ipc.invoke(ipcApiRoute.checkSyncCenter, {});
            if (count > 0) {
                AMessage.warn('下载会清除所有本地数据，请先同步数据上传后再下载！');
            } else {
                showDownloadDialog.value = true;
            }
        };
        const handleLogin = async () => {
            if (username.value && password.value) {
                // 在这里处理实际的登录逻辑，如调用API或验证用户信息
                // 模拟登录成功逻辑
                const encoder = new PasswordEncoder(username.value, 'MD5');
                let encodedPassword = encoder.encode(password.value);
                console.log('encodedPassword:', encodedPassword);
                const params = {
                    userName: username.value,
                    password: encodedPassword
                }
                console.log('params:', params);
                try {
                    const userLogin = await ipc.invoke(ipcApiRoute.getCkUserSqlite, params);
                    if (userLogin) {
                        // alert(`登录成功，欢迎 ${username.value}`);
                        // 将登录状态存储到 localStorage
                        localStorage.setItem('isLoggedIn', 'true');
                        localStorage.setItem('userInfo', JSON.stringify(userLogin));
                        // 跳转到name是 WoodStockList 的页面
                        router.push({ name: 'WoodStockList' });

                    } else {
                        AMessage.error('用户名或密码错误');
                    }
                } catch (e) {
                    AMessage.error('登录失败');
                    console.log('err:', e);
                }
            } else {
                AMessage.warn('请输入用户名和密码');
            }
        };

        const handleDownloadSync = async () => {
            try {
                confirmLoading.value = true;
                let result = await downloadAndExecDbscript('http://localhost:8080/download-data/ckDept');
                result = await downloadAndExecDbscript('http://localhost:8080/download-data/ckUser');
                result = await downloadAndExecDbscript('http://localhost:8080/download-data/ckUserDept');
                result = await downloadAndExecDbscript('http://localhost:8080/download-data/woodNote');
                result = await downloadAndExecDbscript('http://localhost:8080/download-data/woodNoteBill');
                result = await downloadAndExecDbscript('http://localhost:8080/download-data/woodStock');
                console.log('result====================================:', result);
                if (result) {
                    AMessage.success('同步数据成功');
                    showDownloadDialog.value = false;
                } else {
                    AMessage.error('同步数据失败');
                }

            } catch (e) {
                console.log('err:', e);
                AMessage.error('同步数据失败');
            } finally {
                confirmLoading.value = false;
            }

        };

        const downloadAndExecDbscript = async (url) => {
            // 处理同步数据（下载）的逻辑
            // message.warn('同步数据（下载）');
            const response = await axios.get(url, {
                headers: {
                    'token': `123456` // 将 token 添加到 Authorization 头中
                },
                responseType: 'json' // 确保返回的是字符串而非 JSON
            });
            const dbscript = response.data;

            const res = await ipc.invoke(ipcApiRoute.execDbScript, dbscript);
            console.log('res:', res);
            return res;
        }

        const beforeHandleUploadSync = () => {
            // 处理同步数据（上传）的逻辑
            // AMessage.warn('同步数据（上传）');
            showUploadDialog.value = true;
        };

        const cancelDelWoodStock = () => {
            // 取消删除
            showUploadDialog.value = false;
        };

        const handleUploadSync = async () => {
            try {
                confirmLoading.value = true;
                // 获取lk_sync_center数据
                const syncCenterList = await ipc.invoke(ipcApiRoute.getSyncCenterList);
                console.log('syncCenterList:', syncCenterList);
                if (!syncCenterList || syncCenterList.length === 0) {
                    AMessage.warn('没有需要同步上传的数据');
                    return;
                }
                const url = 'http://localhost:8080/upload-data/woodStock';
                const result = await ipc.invoke(ipcApiRoute.uploadOfflineFiles);
                if (!result) {
                    AMessage.error('同步数据上传附件失败');
                    return;
                }
                const response = await axios.post(url, syncCenterList);
                const data = response.data;
                console.log('data:', data);
                // 删除lk_sync_center数据
                await ipc.invoke(ipcApiRoute.deleteSyncCenter, {});

                await handleDownloadSync();
                AMessage.success('同步数据（上传）数据成功');
                // 关闭对话框
                showUploadDialog.value = false;
            } catch (error) {
                console.error('Error:', error);
                AMessage.error('上传数据失败');
            } finally {
                confirmLoading.value = false;
            }
        }

        return {
            username,
            password,
            handleLogin,
            handleDownloadSync,
            handleUploadSync,
            showDownloadDialog,
            beforeHandleDownloadSync,
            showUploadDialog,
            beforeHandleUploadSync,
            cancelDelWoodStock,
            confirmLoading,
        };
    }
};
</script>

<style scoped>
.login-container {
    max-width: 400px;
    margin: 100px auto;
    padding: 20px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    background-color: #fff;
}

h1 {
    text-align: center;
    margin-bottom: 20px;
}

.form-group {
    margin-bottom: 15px;
}

label {
    display: block;
    margin-bottom: 5px;
    font-weight: bold;
}

input {
    width: 100%;
    padding: 8px;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-sizing: border-box;
}

/* 登录按钮样式 */
.login-btn {
    width: 100%;
    padding: 10px;
    border: none;
    background-color: #4276b9;
    color: #fff;
    font-size: 16px;
    cursor: pointer;
    border-radius: 4px;
    transition: background-color 0.3s ease;
}

.login-btn:hover {
    background-color: #359671;
}

/* 同步按钮样式容器 */
.sync-buttons {
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
}

/* 同步数据（下载）按钮样式 */
.download-btn {
    width: 48%;
    padding: 10px;
    border: none;
    background-color: #1890ff;
    /* 蓝色 */
    color: #fff;
    font-size: 16px;
    cursor: pointer;
    border-radius: 4px;
    transition: background-color 0.3s ease;
}

.download-btn:hover {
    background-color: #1677cc;
    /* 深蓝色 */
}

/* 同步数据（上传）按钮样式 */
.upload-btn {
    width: 48%;
    padding: 10px;
    border: none;
    background-color: #f5222d;
    /* 红色 */
    color: #fff;
    font-size: 16px;
    cursor: pointer;
    border-radius: 4px;
    transition: background-color 0.3s ease;
}

.upload-btn:hover {
    background-color: #c41d1f;
    /* 深红色 */
}
</style>